import json
from datetime import datetime

from flask import Flask, Blueprint, Response, request
from flask_jwt_extended import jwt_required
from app.common.commonMessage import CommonMassages
from app.service.UserPortraitService import UserPortraitService
from app.config.db import DBUtils
from app.config.jsonEncoder import CustomJSONEncoder

app = Flask(__name__)
# 创建蓝图
user_portrait_bp = Blueprint('user_portrait_controller', __name__ , url_prefix='/kshx')

user_portrait = UserPortraitService()

# 获取session
db_utils = DBUtils()
session = db_utils.get_session()


# 获取客商画像-基础信息标签页-股东情况
@user_portrait_bp.route('/user-portrait', methods=['GET'])
@jwt_required()
def userportrait():
    # company = request.json.get("company", None)
    company = request.args.get('company')
    if company is not None:
        # 工商信息
        company_base_info = user_portrait.select_company_info(session, company)
        if company_base_info:
            if company_base_info[0]['IS_CYDW']:
                IS_CYDW = int(company_base_info[0]['IS_CYDW'])
            else:
                IS_CYDW = 0
        else:
            IS_CYDW = 0
        year = datetime.now().year
        # 股东信息
        company_executives = user_portrait.select_user_position(session, company)
        # 风险标签
        company_label = user_portrait.select_company_fx_label(session, company, year)
        # 上游企业TOP5
        upstream_top = user_portrait.select_upstream_info(session, company, IS_CYDW)
        # 下游企业TOP5
        downstream_top = user_portrait.select_downstream_info(session, company, IS_CYDW)
        # 历史风险信息
        risk_history = user_portrait.select_risk_history(session, company)
        # 评分信息
        score_info = user_portrait.select_score_info(session, company)

        user_portrait_info = {
            'company_info': company_base_info,
            'company_executives': company_executives,
            'company_fx_label': company_label,
            'upstream_top': upstream_top,
            'downstream_top': downstream_top,
            'risk_history': risk_history,
            'score_info': score_info
        }

        if user_portrait_info is not None:
            result = {
                "code": 200,
                "data": user_portrait_info,
                "message": CommonMassages.CCD_SELECT_SUCCESS.value
            }

        else:
            result = {
                "code": 400,
                "data": None,
                "message": CommonMassages.CCD_SELECT_FAILED.value
            }
    else:
        result = {
            "code": 400,
            "data": None,
            "message": CommonMassages.CCD_SELECT_FAILED.value
        }
    resp_data = json.dumps(result, ensure_ascii=False, cls=CustomJSONEncoder)
    # return Response(resp_data, content_type='application/json')
    return Response(resp_data)
